<script setup>
import { ref, onMounted } from 'vue'
import { sessionApi, newNoteApi, exitApi, menuApi } from '@/commons/api'
import routes from '@/commons/router'
import { CScrollbar } from 'c-scrollbar'
import Msg from '@/components/message'
import MenuTree from '@/components/menu/MenuTree'
import SvgIcon from '@/components/svgicon/SvgIcon'
import Loader from '@/components/loader/Loader'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

// 检查用户权限
// 将先用到的字段列出来
const adminInfo = ref({nickName: ''})
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      adminInfo.value = res.data
      await hasNewNote()
      await listMenu()
    } else {
      localStorage.removeItem('token')
      Msg({ kind: 'error', txt: res.msg })
      routes.replace({path: '/'})
    }
    loadShow.value = false
  } catch(e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统异常，请联系管理员！' + e })
  }
}

// 获取用户是否存在未读消息
const noteInfo = ref({ readed: false, nums: 0 })
const hasNewNote = async () => {
  const res = await newNoteApi()
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    noteInfo.value.readed = res.data > 0
    noteInfo.value.nums = res.data
  }
}

// 工作台菜单
const mainMenu = ref({ selId: '111111111111111111112', menuName: '工作台', menuCode: '10000000', url: '/home' })

// 获取一级菜单
const menuList = ref([])
const menuAct = ref('111111111111111111112')
const listMenu = async () => {
  const res = await menuApi()
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    menuList.value = res.data
    // 选择子系统
    selFstMenu()
  }
}

const sysName = ref('')
const childMenu = ref([])
// 默认选择第一个一级菜单
const selFstMenu = () => {
  sysName.value = menuList.value[0].menuName
  childMenu.value = menuList.value[0].children
}

// 显示子系统选择抽屉
const drawerShow = ref(false)
const showDrawer = () => {
  drawerShow.value = true
}

// 选择子系统
const selDrawer = (id, name) => {
  menuList.value.forEach(menu => {
    if(menu.selId === id) {
      childMenu.value = menu.children
    }
  })
  sysName.value = name
  drawerShow.value = false
  paneList.value = [mainPane]
  toHome()
}

// 关闭子系统选择抽屉
const clsDrawer = () => {
  drawerShow.value = false
}

// tab页签
const mainPane = { title: '工作台', key: '111111111111111111112', path: '/home', closable: false }
const paneList = ref([mainPane])
const paneAct = ref('111111111111111111112')

// 切换标签页
const toTab = (key) => {
  paneAct.value = key
  menuAct.value = key
  paneList.value.forEach(pane => {
    if(pane.key === key) {
      routes.push(pane.path)
    }
  })
}

// 关闭标签页
const closeTab = (targetKey) => {
  let lastIndex = 0
  paneList.value.forEach((pane, i) => {
    if (pane.key === targetKey) {
      lastIndex = i - 1
    }
  })
  paneList.value = paneList.value.filter(pane => pane.key !== targetKey)
  if (paneList.value.length && paneAct.value === targetKey) {
    if (lastIndex >= 0) {
      paneAct.value = paneList.value[lastIndex].key
      menuAct.value = paneList.value[lastIndex].key
      routes.push(paneList.value[lastIndex].path)
    } else {
      paneAct.value = mainPane.key
      menuAct.value = mainPane.key
      routes.push(mainPane.path)
    }
  }
}

// 切换\显示子菜单
const showMenu = (menu) => {
  // 如果没有子菜单
  if(menu && !menu.children && menu.url && menu.url!=='') {
    toPage(menu)
  }
  // 如果有子菜单
  menu.exted = !menu.exted
}

// 收起\展示菜单
const menuHide = ref(false)
const hideMenu = () => {
  menuHide.value = !menuHide.value
}

// 跳转至主页
const toHome = () => {
  toPage(mainMenu.value)
}

// 跳转到消息通知
const toNote = () => {
  toPage({ selId: '111111111111111111113', menuName: '消息通知', menuCode: '10010107', url: '/system/notice' })
}

// 跳转到个人资料修改
const toMine = () => {
  toPage({ selId: '111111111111111111114', menuName: '个人资料', menuCode: '10010108', url: '/system/mine' })
}

// 打开页面
const toPage = (menu) => {
  // 设置左侧导航为激活状态
  menuAct.value = menu.selId
  // 设置Tab页签为激活状态
  paneAct.value = menu.selId
  // 判断Tab页签是否存在
  let exists = false
  paneList.value.forEach(pane => {
    if(pane.key === menu.selId) {
      exists = true
      return
    }
  })
  // 如果Tab页签不存在，则添加
  if(!exists) {
    if(paneList.value.length === 11) {
      // 如果Tab页签已经有11个，则替换第11个
      paneList.value[10] = { title: menu.menuName, key: menu.selId, path: menu.url, closable: true }
    } else {
      // 否则添加到Tab页签
      paneList.value.push({ title: menu.menuName, key: menu.selId, path: menu.url, closable: true })
    }
  }
  // 跳转页面
  routes.push(menu.url)
}

// 用户登出
const exit = async () => {
  await exitApi()
  Msg({ kind: 'success', txt: '恭喜您，安全退出成功！' })
  routes.replace('/')
}
</script>

<template>
  <div class="main-a">
    <!-- 头部Begin -->
    <div class="main-b">
      <div><img src="@/assets/img/3.png" alt="logo" height="30" /></div>
      <div class="main-c" @click="showDrawer" title="选择子系统"><i class="iconfont">&#xe78f;</i> 当前子系统：【{{ sysName }}】</div>
      <div class="main-d" @click="toNote" title="打开消息通知">
        <i class="iconfont">&#xe865;</i>
        <div v-if="noteInfo.readed" class="badge main-p">{{ noteInfo.nums }}</div>
      </div>
      <div class="main-d" @click="toMine" title="修改个人资料"><i class="iconfont">&#xe908;</i> {{ adminInfo.nickName }}【{{ adminInfo.roleName }}】</div>
      <div class="main-d" @click="exit" title="安全退出"><i class="iconfont">&#xe8c6;</i> 安全退出</div>
    </div>
    <!-- 头部End && 中部Begin -->
    <div class="main-e">
      <div class="main-f" v-show="!menuHide">
        <c-scrollbar>
          <!-- 工作台菜单 -->
          <div :class="[menuAct===mainMenu.selId ? 'main-g' : 'main-h']" @click="toHome">
            <div class="main-i"><i class="iconfont mr5">&#xea65;</i></div>
            <div class="main-j">{{ mainMenu.menuName }}</div>
          </div>
          <!-- 根据权限获取的菜单列表 -->
          <div v-for="menu in childMenu" :key="menu.selId">
            <div class="main-h" @click="showMenu(menu)">
              <div v-if="menu.icon"><svg-icon className="mr5 md2" :name="menu.icon" color="#333" width="16" height="16" /></div>
              <div class="main-j">{{ menu.menuName }}</div>
              <div><i class="iconfont" v-html="menu.exted ? '&#xeaa1;' : '&#xeaa6;'"></i></div>
            </div>
            <div v-show="menu.exted && menu.children && menu.children.length>0">
              <menu-tree :menuList="menu.children" :menuAct="menuAct" @toPage="toPage" />
            </div>
          </div>
        </c-scrollbar>
      </div>
      <!-- 内容部分 -->
      <div :class="[menuHide ? 'main-k': 'main-l']">
        <!-- Tab页签 -->
        <div class="main-m">
          <div v-for="pane in paneList" :key="pane.key" :class="[paneAct===pane.key ? 'main-n' : 'main-o']">
            <div class="main-q">
              <div class="main-r dan" @click="toTab(pane.key)" :title="pane.title">{{ pane.title }}</div>
              <div v-if="pane.closable" class="main-s" @click="closeTab(pane.key)"><i class="iconfont">&#xea7f;</i></div>
            </div>
          </div>
        </div>
        <div class="main-t">
          <c-scrollbar><router-view /></c-scrollbar>
        </div>
        <!-- 底部 -->
        <div class="main-u">
          <div class="main-v" @click="hideMenu" title="收起/展开导航菜单"><i class="iconfont" v-html="menuHide ? '&#xe8f8;' : '&#xe8f4;'" /></div>
          <div class="main-w">Copyright &copy; 2024-2025 成电医星（nmgyx.com）</div>
        </div>
      </div>
    </div>
    <!-- 右侧子系统选择抽屉 -->
    <div class="main-x" v-show="drawerShow">
      <div class="main-y">
        <div class="main-z">选择子系统</div>
        <div class="main-aa" @click="clsDrawer"><i class="iconfont fs22">&#xea7f;</i></div>
      </div>
      <c-scrollbar class="main-ab">
        <div class="main-ac" v-for="menu in menuList" @click="selDrawer(menu.selId, menu.menuName)">
          <div v-if="menu.icon"><svg-icon className="mr5 md3" :name="menu.icon" color="#333" width="16" height="14" /></div>
          <div class="main-ad">{{ menu.menuName }}</div>
        </div>
      </c-scrollbar>>
    </div>
    <loader :load-show="loadShow" />
  </div>
</template>

<style scoped>
.main-a {height: 100%; overflow: hidden;}
.main-b {height: 30px; line-height: 30px; padding: 10px 20px; background-color: #0e9be3; display: -webkit-flex; display: flex;}
.main-c {flex-grow: 1; text-align: center; font-size: 16px; color: #FFF; cursor: pointer;}
.main-c:hover {color: #DDD;}
.main-d {padding-left: 20px; font-size: 16px; color: #FFF; cursor: pointer;}
.main-d:hover {color: #DDD;}
.main-e {width: 100%; height: calc(100% - 50px); display: flex; display: -webkit-flex;}
.main-f {width: 208px; height: 100%; background-color: #FFF;}
.main-g {width: 188px; padding: 15px 10px; border-bottom: 1px solid #EEE; display: flex; display: -webkit-flex; align-items: center; cursor: pointer; background-color: #e7f3ff;}
.main-h {width: 188px; padding: 15px 10px; border-bottom: 1px solid #EEE; display: flex; display: -webkit-flex; align-items: center; cursor: pointer;}
.main-h:hover {background-color: #e7f3ff;}
.main-j {flex-grow: 1; font-size: 16px;}
.main-k {width: 100%; height: calc(100% - 8px);}
.main-l {width: calc(100% - 208px); height: 100%;}
.main-m {height: 35px; line-height: 35px; padding: 5px 4px 0 4px; background-color: #FFF; display: flex; display: -webkit-flex; flex-wrap: nowrap;}
.main-n {width: 78px; flex-shrink: 0; height: 34px; padding: 0 10px; margin: 0 4px; border: 0; border-left: 1px solid #F0F0F0; border-top: 1px solid #F0F0F0; border-right: 1px solid #F0F0F0; border-top-left-radius: 10px; border-top-right-radius: 10px; background-color: #F0F0F0; color: #0e9be3; cursor: pointer;}
.main-o {width: 78px; flex-shrink: 0; height: 34px; padding: 0 10px; margin: 0 4px; border: 0; border-left: 1px solid #F0F0F0; border-top: 1px solid #F0F0F0; border-right: 1px solid #F0F0F0; border-top-left-radius: 10px; border-top-right-radius: 10px; background-color: #FFFFFF; color: #666666; cursor: pointer;}
.main-o:hover {background-color: #F0F0F0; color: #0e9be3;}
.main-p {margin: -30px 0 0 14px; line-height: normal;}
.main-q {width: 100%; display: inline-flex; display: -webkit-inline-flex;}
.main-r {flex-grow: 1; text-align: center;}
.main-s {width: 14px; color: #666;}
.main-s:hover {color: #0e9be3;}
.main-t {width: calc(100% - 16px); height: calc(100% - 91px); margin: 8px; background-color: #FFF;}
.main-u {height: 35px; line-height: 35px; margin: 0 8px; background-color: #FFF; text-align: center; display: flex; display: -webkit-flex;}
.main-v {padding: 0 5px; font-size: 20px; border-right: 1px solid #DDD; cursor: pointer;}
.main-v:hover {color: #0e9be3;}
.main-w {flex-grow: 1;}
.main-x {position: fixed; top: 0; right: 0; width: 200px; height: 100%; background-color: #FFF; z-index: 2; box-shadow: -1px 0 3px rgba(0, 0, 0, 0.1);}
.main-y {padding: 10px; display: flex; display: -webkit-flex; border-bottom: 1px #CCC solid;}
.main-z {flex-grow: 1; font-size: 18px;}
.main-aa {cursor: pointer;} 
.main-aa:hover {color: #0e9be3;}
.main-ab {height: calc(100% - 40px);}
.main-ac {height: 49px; line-height: 50px; padding: 0 30px; display: flex; display: -webkit-flex; cursor: pointer; border-bottom: 1px #f0f0f0 solid;}
.main-ac:hover {background-color: #e7f3ff;}
.main-ad {flex-grow: 1; font-size: 16px;}
</style>
